package com.deep.deepenterpise.service.task.impl;

import com.deep.deepenterpise.common.DrGson;
import com.deep.deepenterpise.common.DrTransactionCommon;
import com.deep.deepenterpise.common.code.DrCodeMsg;
import com.deep.deepenterpise.common.enums.DrBaseEnum;
import com.deep.deepenterpise.common.enums.DrGasTypeEnum;
import com.deep.deepenterpise.common.enums.DrOrderTypeEnum;
import com.deep.deepenterpise.common.map.DrMapConstant;
import com.deep.deepenterpise.common.redis.GasKey;
import com.deep.deepenterpise.common.util.DrCommonUtil;
import com.deep.deepenterpise.common.util.DrDateUtil;
import com.deep.deepenterpise.dao.*;
import com.deep.deepenterpise.model.entity.DrCheckItem;
import com.deep.deepenterpise.model.entity.DrSysSynchronize;
import com.deep.deepenterpise.model.entity.DrSysSynchronizeOrder;
import com.deep.deepenterpise.model.to.gas.*;
import com.deep.deepenterpise.model.vo.gas.*;
import com.deep.deepenterpise.model.vo.unit.DrDangerItemVo;
import com.deep.deepenterpise.model.vo.unit.DrDangerVo;
import com.deep.deepenterpise.model.vo.unit.DrSysMapVo;
import com.deep.deepenterpise.model.vo.unit.DrUnitSecretVo;
import com.deep.deepenterpise.service.gas.IDrGovernmentApi;
import com.deep.deepenterpise.service.task.IDrTaskMethod;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xyz
 * @version 1.0
 * @title TaskMethod
 * @description
 * @create 2024/5/16 19:18
 */
@Service
@Slf4j
@AllArgsConstructor
public class DrTaskMethod implements IDrTaskMethod {
    private final IDrGovernmentApi iDrGovernmentApi;

    private final StringRedisTemplate stringRedisTemplate;

    private final DrTransactionCommon drTransactionCommon;

    private final DrSysUnitMapper drSysUnitMapper;
    private final DrSysStaffMapper drSysStaffMapper;
    private final DrSysCartMapper drSysCartMapper;
    private final DrSysBottleFillingMapper drSysBottleFillingMapper;
    private final DrCheckHistoryMapper drCheckHistoryMapper;
    private final DrSysSynchronizeMapper drSysSynchronizeMapper;
    private final DrCheckItemMapper drCheckItemMapper;
    private final DrBottleLogMapper drBottleLogMapper;
    private final DrSysBottleMapper drSysBottleMapper;
    private final DrSysMemberMapper drSysMemberMapper;
    private final DrSysMapMapper drSysMapMapper;
    private final DrGoodsOrderMapper drGoodsOrderMapper;
    private final DrSysSynchronizeOrderMapper drSysSynchronizeOrderMapper;
    private final DrDangerHistoryMapper drDangerHistoryMapper;
    private final DrDangerHistoryItemMapper drDangerHistoryItemMapper;
    private final DrGoodsOrderEvaluationMapper drGoodsOrderEvaluationMapper;

    /**
     * @Auth xyz
     * @Desc //TODO 同步企业信息
     * @Time 15:28 2024/5/15
     */
    @Override
    public void drAddUnitMethod(String drMethod) {
        // 获取企业信息
        List<DrAddUnitTo> drAddUnitTos = drSysUnitMapper.findDrAddUnitToListByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drAddUnitTos)) {
            return;
        }
        for (DrAddUnitTo drAddUnitTo : drAddUnitTos) {
            String drUnitKey = drAddUnitTo.getDrUnitCode();
            String drSecret = drAddUnitTo.getDrSecret();
            // 如果为空，则不执行
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            // 调用接口
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddUnit(drAddUnitTo, drUnitKey);
            if (drResult != null && !drResult.success()) {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步人员信息
     * @Time 15:51 2024/5/15
     */
    @Override
    public void drAddPersonnelMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取人员记录
            List<DrAddPersonnelTo> drAddPersonnelTos = drSysStaffMapper
                    .findDrAddPersonnelToByDrUnitCode(drUnitSecretVo.getDrUnitKey());
            if (CollectionUtils.isEmpty(drAddPersonnelTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddPersonnel(drAddPersonnelTos, drUnitKey);
            if (drResult != null && !drResult.success()) {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步车辆信息
     * @Time 17:02 2024/5/15
     */
    @Override
    public void drAddCartMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取车辆记录
            List<DrAddCartTo> drAddCartTos = drSysCartMapper.findDrAddCartToByDrUnitKey(drUnitSecretVo.getDrUnitKey());
            if (CollectionUtils.isEmpty(drAddCartTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddCart(drAddCartTos, drUnitKey);
            if (drResult != null && !drResult.success()) {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步气瓶信息
     * @Time 16:29 2024/5/24
     * @Param [drMethod]
     */
    @Override
    public void draAddGasCylinderMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
            // 获取钢瓶数据
            List<DrAddGasCylinderTo> drGasCylinderTos = drSysBottleMapper
                    .findByDrUnitKeyAndDrIdGreaterThanAndLimit(drUnitSecretVo.getDrUnitKey(),
                            drSysSynchronize.getDrCurrentId(), 500);
            if (CollectionUtils.isEmpty(drGasCylinderTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddGasCylinder(drGasCylinderTos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            // 同步记录
            if (drResult.success()) {
                // 同步记录
                int drSize = drGasCylinderTos.size();
                synchronize(drSysSynchronize, drSize, drGasCylinderTos.get(drSize - 1).getDrId());
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步评级记录
     * @Time 10:20 2024/6/29
     * @Param [drMethod]
     */
    @Override
    public void drAddEvaMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            Long drUpdateTime = drSysSynchronize.getDrUpdateTime();
            drUpdateTime = drUpdateTime == null ? 0 : drUpdateTime;

            // 获取钢瓶数据
            List<DrAddEvaVo> drAddEvaVos = drGoodsOrderEvaluationMapper.findByDrUnitKeyAndCreateTimeGreaterThanLimit(
                    drUnitSecretVo.getDrUnitKey(), drUpdateTime, 500);
            if (CollectionUtils.isEmpty(drAddEvaVos)) {
                synchronize(drSysSynchronize);
                continue;
            }

            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drResult = iDrGovernmentApi.postAddEva(drAddEvaVos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            // 同步记录
            if (drResult.success()) {
                // 同步记录
                int drSize = drAddEvaVos.size();
                drSysSynchronize.setDrUpdateTime(drAddEvaVos.get(drSize - 1).getDrCreateTime());
                synchronize(drSysSynchronize, drSize, 0);
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步会员信息
     * @Time 15:59 2024/5/29
     * @Param [drMethod]
     */
    @Override
    public void drAddMemberMethod(String drMethod) {
        DrSysSynchronize drSysSynchronize = getSysSynchronize(DrBaseEnum.BASE_UNIT.getDrCode(), drMethod);
        drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
        // 获取会员信息
        List<DrAddMemberTo> drAddMemberTos = drSysMemberMapper
                .findByIdGreaterThanLimit(drSysSynchronize.getDrCurrentId(), 500);
        if (CollectionUtils.isEmpty(drAddMemberTos)) {
            synchronize(drSysSynchronize);
            return;
        }

        for (DrAddMemberTo drAddMemberTo : drAddMemberTos) {
            DrAddMemberTo.DrCardTo card = getCard(drAddMemberTo.getDrCardStr());
            if (card != null) {
                drAddMemberTo.setDrCard(card);
                drAddMemberTo.setDrCardStr(null);
            }
        }

        DrGasResultVo drGasResultVo = iDrGovernmentApi.postDrAddMember(drAddMemberTos);
        if (drGasResultVo == null) {
            return;
        }
        // 同步记录
        if (drGasResultVo.success()) {
            // 同步记录
            int drSize = drAddMemberTos.size();
            synchronize(drSysSynchronize, drSize, drAddMemberTos.get(drSize - 1).getDrId());
        } else {
            log.error("[政府端API-同步会员信息] 失败, 原因: {}", drGasResultVo.getDrMsg());
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 上传订单错误记录
     * @Time 10:36 2024/6/28
     * @Param [drMethod]
     */
    @Override
    public void drAddOrderErrorMethod(String drMethod) {
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        // 获取钢瓶型号
        List<DrSysMapVo> drSysMapVos = drSysMapMapper.findByDrParentKey(DrMapConstant.GAS_FORMAT);
        if (CollectionUtils.isEmpty(drSysMapVos)) {
            log.warn("[政府端API-同步异常订单信息] 未找到钢瓶规格配置");
            return;
        }
        Map<String, DrSysMapVo> formatMap = drSysMapVos.stream()
                .collect(Collectors.toMap(DrSysMapVo::getDrKey, vo -> vo));
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取token
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            List<DrAddOrderTo> drAddOrderTos = drGoodsOrderMapper
                    .findErrByDrUnitKeySynOrderNoIsNull(drUnitSecretVo.getDrUnitKey());
            if (CollectionUtils.isEmpty(drAddOrderTos)) {
                continue;
            }
            handleOrder(drUnitKey, gasToken, drAddOrderTos, formatMap);
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步订单信息
     * @Time 11:18 2024/6/4
     * @Param [drMethod]
     */
    @Override
    public void drAddOrderMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        // 获取钢瓶型号
        List<DrSysMapVo> drSysMapVos = drSysMapMapper.findByDrParentKey(DrMapConstant.GAS_FORMAT);
        if (CollectionUtils.isEmpty(drSysMapVos)) {
            log.warn("[政府端API-同步订单信息] 未找到钢瓶规格配置");
            return;
        }
        Map<String, DrSysMapVo> formatMap = drSysMapVos.stream()
                .collect(Collectors.toMap(DrSysMapVo::getDrKey, vo -> vo));
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取token
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            List<DrAddOrderTo> drAddOrderTos = drGoodsOrderMapper
                    .findByDrUnitKeySynOrderNoIsNull(drUnitSecretVo.getDrUnitKey());
            if (CollectionUtils.isEmpty(drAddOrderTos)) {
                continue;
            }
            handleOrder(drUnitKey, gasToken, drAddOrderTos, formatMap);
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 处理订单
     * @Time 14:42 2024/6/4
     * @Param [drAddOrderTos, formatMap]
     */
    private void handleOrder(String drUnitKey, String gasToken, List<DrAddOrderTo> drAddOrderTos,
                             Map<String, DrSysMapVo> formatMap) {
        List<String> orderNoList = new ArrayList<>(drAddOrderTos.size());
        for (DrAddOrderTo drAddOrderTo : drAddOrderTos) {
            // 保存订单号
            orderNoList.add(drAddOrderTo.getDrOrderNo());

            // 判断补贴
            Integer drDiscount = drAddOrderTo.getDrDiscount();
            drAddOrderTo.setDrType(drDiscount == null ? 0 : drDiscount);

            List<DrAddOrderTo.DrBottleDetailTo> drBottleDetails = drAddOrderTo.getDrBottleDetails();
            if (CollectionUtils.isEmpty(drBottleDetails)) {
                drAddOrderTo.setDrBottleNum(0);
                continue;
            }
            drAddOrderTo.setDrBottleNum(drBottleDetails.size());

            BigDecimal totalGasWeight = BigDecimal.ZERO;
            for (DrAddOrderTo.DrBottleDetailTo drBottleDetail : drBottleDetails) {
                DrSysMapVo drSysMapVo = formatMap.get(drBottleDetail.getDrFormat());
                if (drSysMapVo == null) {
                    drBottleDetail.setDrFormat("0");
                    continue;
                }
                drBottleDetail.setDrFormat(drSysMapVo.getDrName());

                if (drAddOrderTo.getDrOrderType() > 3) {
                    continue;
                }

                if (DrGasTypeEnum.HEAVY.compare(drBottleDetail.getDrGasState())) {
                    totalGasWeight = totalGasWeight.add(new BigDecimal(drSysMapVo.getDrModule()));
                }
            }

            drAddOrderTo.setDrGasWeight(totalGasWeight);
        }

        DrOrderVo drOrderVo = iDrGovernmentApi.postDrAddOrder(drAddOrderTos, drUnitKey);
        if (drOrderVo == null) {
            return;
        }
        if (drOrderVo.success()) {
            saveSynOrder(drOrderVo.getDrData(), orderNoList);
        } else {
            fail(drOrderVo.getDrCode(), drOrderVo.getDrMsg(), drUnitKey, gasToken);
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步订单信息
     * @Time 14:57 2024/6/28
     * @Param [drData, orderNoList]
     */
    private void saveSynOrder(DrOrderMsgVo drData, List<String> orderNoList) {
        List<String> drError = drData.getDrError();
        if (!CollectionUtils.isEmpty(drError)) {
            orderNoList.removeAll(drError);
        }
        if (CollectionUtils.isEmpty(orderNoList)) {
            return;
        }
        for (String drOrderNo : orderNoList) {
            // 保存订单号
            try {
                drSysSynchronizeOrderMapper.insert(new DrSysSynchronizeOrder(drOrderNo));
            }
            // 这里不需要事务，只记录错误日志
            catch (Exception e) {
                log.error("[政府端API-同步订单信息] 保存订单号失败，error：{}", DrCommonUtil.drGetStackTraceInfo(e));
            }
        }
    }

    /**
     * @return com.deep.deepenterpise.model.to.gas.DrAddMemberTo.DrCardTo
     * @Auth xyz
     * @Desc //TODO 获取认证信息
     * @Time 16:18 2024/5/29
     * @Param [drCardStr]
     */
    private DrAddMemberTo.DrCardTo getCard(String drCardStr) {
        if (StringUtils.isBlank(drCardStr)) {
            return null;
        }
        DrCardTo drCardTo = DrGson.parseObject(drCardStr, DrCardTo.class);
        DrAddMemberTo.DrCardTo deMemberDrCardTo = new DrAddMemberTo.DrCardTo();
        List<DrCardTo.DrItem> business = drCardTo.getBusiness();
        List<DrCardTo.DrItem> house = drCardTo.getHouse();
        List<DrCardTo.DrItem> idCard1 = drCardTo.getIdcard1();
        List<DrCardTo.DrItem> idCard2 = drCardTo.getIdcard2();
        if (!CollectionUtils.isEmpty(business)) {
            deMemberDrCardTo.setDrBusiness(Collections
                    .singletonList(new DrAddMemberTo.DrCardItemTo(business.get(0).getName(),
                            business.get(0).getUrl())));
        } else if (!CollectionUtils.isEmpty(house)) {
            deMemberDrCardTo.setDrIndustry(Collections
                    .singletonList(new DrAddMemberTo.DrCardItemTo(house.get(0).getName(),
                            house.get(0).getUrl())));
        } else if (!CollectionUtils.isEmpty(idCard1)) {
            List<DrAddMemberTo.DrCardItemTo> drIdCard = new ArrayList<>();
            drIdCard.add(new DrAddMemberTo.DrCardItemTo(idCard1.get(0).getName(), idCard1.get(0).getUrl()));
            if (!CollectionUtils.isEmpty(idCard2)) {
                drIdCard.add(new DrAddMemberTo.DrCardItemTo(idCard2.get(0).getName(), idCard2.get(0).getUrl()));
            }
            deMemberDrCardTo.setDrIdcard(drIdCard);
        } else {
            return null;
        }
        return deMemberDrCardTo;
    }

    /**
     * @Auth xyz
     * @Desc //TODO 充装记录上传
     * @Time 15:29 2024/5/15
     */
    @Override
    public void drAddRefillNoticeMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取同步记录
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
            // 获取充装记录
            List<DrAddRefillNoticeTo> drAddRefillNoticeTos = drSysBottleFillingMapper
                    .findNoticeToByDrUnitKeyAndDrIdIsMoreThan(drUnitSecretVo.getDrUnitKey(),
                            drSysSynchronize.getDrCurrentId());
            if (CollectionUtils.isEmpty(drAddRefillNoticeTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddRefillNotice(drAddRefillNoticeTos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            // 同步记录
            if (drResult.success()) {
                // 同步记录
                synchronize(drSysSynchronize, drAddRefillNoticeTos.size(), drAddRefillNoticeTos.get(0).getDrId());
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 充装记录后上传
     * @Time 15:29 2024/5/15
     */
    @Override
    public void drAddRefillAfterMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
            // 获取充装记录
            List<DrAddRefillAfterTo> drAddRefillAfterTos = drSysBottleFillingMapper
                    .findAfterByDrUnitKeyAndDrIdIsMoreThan(drUnitSecretVo.getDrUnitKey(),
                            drSysSynchronize.getDrCurrentId());
            if (CollectionUtils.isEmpty(drAddRefillAfterTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddRefillAfter(drAddRefillAfterTos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            // 同步记录
            if (drResult.success()) {
                // 同步记录
                synchronize(drSysSynchronize, drAddRefillAfterTos.size(), drAddRefillAfterTos.get(0).getDrId());
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 充装记录前上传
     * @Time 15:29 2024/5/15
     */
    @Override
    public void drAddRefillBeforeMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取同步记录
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
            // 获取充装记录
            List<DrAddRefillBeforeTo> drAddRefillBeforeTos = drSysBottleFillingMapper
                    .findBeforeByDrUnitKeyAndDrIdIsMoreThan(drUnitSecretVo.getDrUnitKey(),
                            drSysSynchronize.getDrCurrentId());
            if (CollectionUtils.isEmpty(drAddRefillBeforeTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddRefillBefore(drAddRefillBeforeTos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            if (drResult.success()) {
                // 同步记录
                synchronize(drSysSynchronize, drAddRefillBeforeTos.size(), drAddRefillBeforeTos.get(0).getDrId());
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 随瓶安检记录上传
     * @Time 14:06 2024/5/16
     */
    @Override
    public void drAddCheckBottleMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取同步记录
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
            // 获取充装记录
            List<DrAddCheckHistoryTo> drAddCheckBottleTos = drCheckHistoryMapper
                    .findCheckBottleByDrUnitKeyAndDrIdIsMoreThanAndDrTypeNot(drUnitSecretVo.getDrUnitKey(),
                            drSysSynchronize.getDrCurrentId(), DrOrderTypeEnum.CHECK_HOUSE.getDrType());
            if (CollectionUtils.isEmpty(drAddCheckBottleTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            parseDrContent(drAddCheckBottleTos);
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddCheckBottle(drAddCheckBottleTos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            if (drResult.success()) {
                // 同步记录
                synchronize(drSysSynchronize, drAddCheckBottleTos.size(), drAddCheckBottleTos.get(0).getDrId());
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步入户检查记录
     * @Time 08:41 2024/6/14
     * @Param [drMethod]
     */
    @Override
    public void drAddCheckHouseMethod(String drMethod) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
            List<DrAddCheckHistoryTo> drAddCheckBottleTos = drCheckHistoryMapper
                    .findCheckHouseByDrUnitKeyAndDrIdIsMoreThanAndDrType(drUnitSecretVo.getDrUnitKey(),
                            drSysSynchronize.getDrCurrentId(), DrOrderTypeEnum.CHECK_HOUSE.getDrType());
            if (CollectionUtils.isEmpty(drAddCheckBottleTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            parseDrContent(drAddCheckBottleTos);
            DrGasResultVo drResult = iDrGovernmentApi.postDrAddCheckHouse(drAddCheckBottleTos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            if (drResult.success()) {
                synchronize(drSysSynchronize, drAddCheckBottleTos.size(), drAddCheckBottleTos.get(0).getDrId());
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 解析数据
     * @Time 09:45 2024/6/14
     * @Param [to]
     */
    private void parseDrContent(List<DrAddCheckHistoryTo> drAddCheckBottleTos) {
        // 数据处理
        for (DrAddCheckHistoryTo to : drAddCheckBottleTos) {
            parseDrContent(to, to.getDrId());
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 获取检查项内容
     * @Time 15:50 2024/5/23
     * @Param [drCheckOrderNum]
     */
    private void parseDrContent(DrAddCheckHistoryTo to, Integer drId) {
        String drContent = to.getDrContent();
        if (StringUtils.isBlank(drContent)) {
            return;
        }
        to.setDrContent(null);

        DrContentVo drContentVo;
        try {
            drContentVo = DrGson.parseObject(drContent, DrContentVo.class);
        } catch (Exception e) {
            log.error("[政府端API-安检记录] 解析异常，drId: {}", drId);
            return;
        }

        to.setDrIllegal(drContentVo);
        List<DrItemVo> drItems = drContentVo.getDrItem();
        if (!CollectionUtils.isEmpty(drItems)) {
            to.setDrCheckWarn(drItems.size());
        } else {
            to.setDrCheckWarn(0);
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 更新安检条目
     * @Time 08:58 2024/5/17
     * @Param [drMethod]
     */
    @Override
    public void drAddCheckItemMethod(String drMethod) {
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取所有检查项
            List<DrCheckItem> drCheckItems = drCheckItemMapper.findByDrUnitKey(drUnitSecretVo.getDrUnitKey());
            if (CollectionUtils.isEmpty(drCheckItems)) {
                return;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrGasResultVo drGasResultVo = iDrGovernmentApi.postDrAddCheckItem(drCheckItems, drUnitKey);
            if (drGasResultVo == null) {
                continue;
            }
            // 同步记录
            if (!drGasResultVo.success()) {
                fail(drGasResultVo.getDrCode(), drGasResultVo.getDrMsg(), drUnitKey, gasToken);
            }
        }

    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步充装站气瓶日志（出入库）记录
     * @Time 11:28 2024/5/20
     * @Param [drMethod]
     */
    @Override
    public void drAddBottleLogMethod(String drMethod, String drType) {
        // 获取企业信息
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取同步记录
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
            // 获取充装记录
            List<DrAddBottleLogTo> drAddBottleLogTos = drBottleLogMapper
                    .findDrAddBottleLogToByDrTypeAndDrUnitKeyAndDrZzIsZero(drType, drUnitSecretVo.getDrUnitKey(),
                            drSysSynchronize.getDrCurrentId());
            if (CollectionUtils.isEmpty(drAddBottleLogTos)) {
                continue;
            }
            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }
            DrBottleLogVo drBottleLogVo = iDrGovernmentApi.postDrAddBottleLog(drAddBottleLogTos, drUnitKey);
            if (drBottleLogVo == null) {
                continue;
            }
            // 同步记录
            if (drBottleLogVo.success()) {
                // 同步记录
                synchronize(drSysSynchronize, drAddBottleLogTos.size(), drAddBottleLogTos.get(0).getDrId());
            } else {
                fail(drBottleLogVo.getDrCode(), drBottleLogVo.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 上传钢瓶流转日志
     * @Time 16:18 2024/6/14
     * @Param [addBottleLoopLog]
     */
    @Override
    public void drAddBottleLoopLogMethod(String drMethod) {
        // 获取同步记录
        DrSysSynchronize drSysSynchronize = getSysSynchronize(DrBaseEnum.BASE_UNIT.getDrCode(), drMethod);
        drSysSynchronize.setDrLastId(drSysSynchronize.getDrCurrentId());
        // 获取充装记录
        List<DrAddBottleLoopLogTo> drAddBottleLoopLogTos = drBottleLogMapper
                .findDrAddBottleLoopLogToByDrIdGreaterThenDrLimit(drSysSynchronize.getDrCurrentId(), 500);
        if (CollectionUtils.isEmpty(drAddBottleLoopLogTos)) {
            return;
        }
        DrGasResultVo drResult = iDrGovernmentApi.postDrAddBottleLoopLog(drAddBottleLoopLogTos, null);
        if (drResult == null) {
            return;
        }
        if (drResult.success()) {
            // 同步记录
            int size = drAddBottleLoopLogTos.size();
            synchronize(drSysSynchronize, size, drAddBottleLoopLogTos.get(size - 1).getDrId());
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 上传隐患记录
     * @Time 13:02 2024/6/26
     * @Param [drMethod]
     */
    @Override
    public void drAddDangerMethod(String drMethod) {
        List<DrUnitSecretVo> drUnitSecretVos = drSysUnitMapper.findDrUnitSecretVoByDrUnitCodeIsNotNull();
        if (CollectionUtils.isEmpty(drUnitSecretVos)) {
            return;
        }
        long drNowTime = DrDateUtil.getCurrentSeconds();
        for (DrUnitSecretVo drUnitSecretVo : drUnitSecretVos) {
            String drUnitKey = drUnitSecretVo.getDrUnitCode();
            String drSecret = drUnitSecretVo.getDrSecret();
            // 获取同步记录
            DrSysSynchronize drSysSynchronize = getSysSynchronize(drUnitSecretVo.getDrUnitKey(), drMethod);
            Long drUpdateTime = drSysSynchronize.getDrUpdateTime();
            drUpdateTime = drUpdateTime == null ? 0 : drUpdateTime;
            drSysSynchronize.setDrUpdateTime(drNowTime);

            List<DrSynDangerHistoryVo> drSynDangerHistoryVos = drDangerHistoryMapper
                    .findDrSynDangerByDrUnitKeyAndDrUpdateTimeGreaterThan(drUnitSecretVo.getDrUnitKey(), drUpdateTime);

            if (CollectionUtils.isEmpty(drSynDangerHistoryVos)) {
                continue;
            }

            String gasToken = iDrGovernmentApi.getToken(drMethod, drUnitKey, drSecret);
            if (StringUtils.isBlank(gasToken)) {
                continue;
            }

            for (DrSynDangerHistoryVo drSynDangerHistoryVo : drSynDangerHistoryVos) {
                String drRectify = drSynDangerHistoryVo.getDrRectifyStr();
                if (StringUtils.isNotBlank(drRectify)) {
                    drSynDangerHistoryVo.setDrRectifyStr(null);
                    drSynDangerHistoryVo.setDrRectify(DrGson.parseObject(drRectify, DrDangerVo.class));
                } else {
                    drSynDangerHistoryVo.setDrRectify(new DrDangerVo());
                }
                List<DrDangerItemVo> drDangerItemVos = drDangerHistoryItemMapper
                        .findByDrSynDangerVoDrDangerSlaveNum(drSynDangerHistoryVo.getDrDangerSlaveNum());
                if (CollectionUtils.isEmpty(drDangerItemVos)) {
                    drSynDangerHistoryVo.setDrDanger(new DrDangerVo());
                    continue;
                }
                DrDangerVo drDangerVo = new DrDangerVo();
                drDangerVo.setDrDangerItems(drDangerItemVos);
                String drPhotoStr = drSynDangerHistoryVo.getDrPhotoStr();
                if (StringUtils.isNotBlank(drPhotoStr)) {
                    drSynDangerHistoryVo.setDrPhotoStr(null);
                    drDangerVo.setDrDangerPhoto(DrGson.parseArray(drPhotoStr));
                } else {
                    drDangerVo.setDrDangerPhoto(Collections.emptyList());
                }
                drSynDangerHistoryVo.setDrDanger(drDangerVo);
            }

            DrGasResultVo drResult = iDrGovernmentApi.postDrAddDanger(drSynDangerHistoryVos, drUnitKey);
            if (drResult == null) {
                continue;
            }
            // 同步记录
            if (drResult.success()) {
                // 同步记录
                synchronize(drSysSynchronize, drSynDangerHistoryVos.size(), 0);
            } else {
                fail(drResult.getDrCode(), drResult.getDrMsg(), drUnitKey, gasToken);
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 更新检查项
     * @Time 16:22 2024/6/26
     * @Param [drMethod]
     */
    @Override
    @Transactional
    public void drCheckItemMethod(String drMethod) {
        DrGasCheckItemVo drResult = iDrGovernmentApi.getDrCheckItem();
        if (drResult == null) {
            return;
        }
        if (!drResult.success()) {
            return;
        }
        List<DrCheckItemVo> drData = drResult.getDrData();
        for (DrCheckItemVo drDatum : drData) {
            drCheckItemMapper.insertOrUpdate(drDatum);
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 失败处理
     * @Time 16:21 2024/5/23
     * @Param [drCode, drMsg, drUnitKey, gasToken]
     */
    public void fail(Integer drCode, String drMsg, String drUnitKey, String gasToken) {
        log.error("[政府端API] drUnitKey:{}, drCode:{}, drMsg:{}", drUnitKey, drCode, drMsg);
        // 不是token过期 不处理
        if (!DrCodeMsg.TOKEN_EXPIRE_ERR.compare(drCode)) {
            return;
        }
        synchronized (drUnitKey.intern()) {
            String token = stringRedisTemplate.opsForValue().get(GasKey.LOGIN_TOKEN_KEY
                    .withSuffix(drUnitKey).getKey());
            // token为空 不处理
            if (StringUtils.isBlank(token)) {
                return;
            }
            // token相同 删除
            if (token.equals(gasToken)) {
                stringRedisTemplate.delete(GasKey.LOGIN_TOKEN_KEY.withSuffix(drUnitKey).getKey());
            }
        }
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步记录
     * @Time 12:01 2024/6/28
     * @Param [drSynchronize]
     */
    private void synchronize(DrSysSynchronize drSynchronize) {
        drSynchronize.setDrLastId(0);
        drSynchronize.setDrCurrentId(0);
        drSynchronize.setDrSize(0);
        drSynchronize.setDrUpdateTime(0L);
        saveSynchronize(drSynchronize);
    }

    /**
     * @Auth xyz
     * @Desc //TODO 同步记录
     * @Time 16:03 2024/5/16
     */
    private void synchronize(DrSysSynchronize drSynchronize, Integer size, Integer currentId) {
        if (drSynchronize == null) {
            return;
        }
        // 同步记录
        drSynchronize.setDrCurrentId(currentId);
        drSynchronize.setDrSize(drSynchronize.getDrSize() + size);
        saveSynchronize(drSynchronize);
    }

    /**
     * @Auth xyz
     * @Desc //TODO 保存同步记录
     * @Time 12:00 2024/6/28
     * @Param [drSysSynchronize]
     */
    private void saveSynchronize(DrSysSynchronize drSysSynchronize) {
        boolean success = drTransactionCommon.submit("同步记录更新", () -> {
            if (drSysSynchronize.getDrId() == null) {
                // 新增
                drSysSynchronizeMapper.insert(drSysSynchronize);
            } else {
                // 更新
                drSysSynchronizeMapper.update(drSysSynchronize);
            }
        });
        if (!success) {
            // 同步失败
            log.error("[政府端API] synchronize error, drUnitKey:{}, method:{}，lastId:{}，currentId:{}",
                    drSysSynchronize.getDrUnitKey(), drSysSynchronize.getDrMethod(), drSysSynchronize.getDrLastId(),
                    drSysSynchronize.getDrCurrentId());
        }

    }

    /**
     * @return DrSysSynchronize
     * @Auth xyz
     * @Desc //TODO 获取同步记录
     * @Time 15:32 2024/5/16
     * @Param [drUnitKey, method]
     */
    private DrSysSynchronize getSysSynchronize(String drUnitKey, String method) {
        DrSysSynchronize drSysSynchronize = drSysSynchronizeMapper
                .findDrSynchronizeBoByUnitKeyAndMethod(drUnitKey, method);
        if (drSysSynchronize == null) {
            return new DrSysSynchronize(drUnitKey, method);
        }
        return drSysSynchronize;
    }
}
